#LAN Transmission
#coding:utf-8
import socket,struct,os,threading,Queue
from tl import *
class Server(object):

    def __init__(self, port):
        super(Server, self).__init__()
        addr = ("0.0.0.0",port)
        self.error = False
        #try:
        self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.s.bind(addr)
        #except Exception,e:
            #print Exception,e
            #raise Exception("Error To Bind")
    def Listen(self,maxthread):
        self.s.listen(maxthread)
        while 1:
            client, addr = self.s.accept()
            msg = client.recv(2048)
            print msg+"\n"
            msg2 = txt_("Start:",":End",msg)
            if msg2 == None:
                continue
            client.send("ok")
            array = str(msg2).split("||||")
            #FileDate = msg[msg.find(":End")+1:]
            FileDate = client.recv(int(array[1]))
            print os.path.join(GetSVN_PATH(),array[2],array[0])
            if os.path.isdir(os.path.join(GetSVN_PATH(),array[2])) == False:os.mkdir(os.path.join(GetSVN_PATH(),array[2]))
            with open(os.path.join(GetSVN_PATH(),array[2],array[0])) as f:
                f.write(FileDate)
            print "Finish:"+array[0]
            client.close()


class Client(object):

    def __init__(self):
        super(Client, self).__init__()
        self.queue = Queue.Queue()
    def Send(self,target_,thread=0,):
        if self.queue.empty():
            print "No File in List.Print AppendQueue."
            return

        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client.connect((target_[0], target_[1]))
            client.close()
        except Exception,e:
            print Exception,e
            print "Cannot connect Server:%s Pord:%s"%(target_[0],target_[1])
            return
        Thread_List = []
        if thread == 0:
            self.__SendThread(target_)
        else:
            for _ in range(0,thread):
                Thread_List.append(threading.Thread(target=self.__SendThread, args=(target_,)))
            for i in Thread_List:
                i.start()
            while self.queue.empty():
                print "Poll..."
            print "Sending......Finish"
    def __SendThread(self,target_):
        print target_,self.queue.empty()
        while self.queue.empty() == False:
            tmp = self.queue.get()
            print tmp
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            print "Sending:"+tmp[0]
            client.connect((target_[0], target_[1]))
            with open(tmp[0],"rb") as f:
                FileSize = GetFileSize(f)
                if FileSize != 0:
                    client.send("Start:"+GetFileName(tmp[0])+"||||"+str(FileSize)+"||||"+tmp[1]+":End")
                    client.recv(1)
                    client.send(f.read())
            print "SendOK:"+tmp[0]
            client.close()
    def Check(self): pass
    def AppendQueue(self,path,other_p=""):

        if os.path.isfile(path):
            belong = path[path[:path.rindex("\\")].rindex('\\')+1:path.rindex("\\")]
            print path,belong
            self.queue.put([path,belong])
        else:
            floders,files = gci(path)

            if files != []:
                for i in files:
                    if other_p =="":
                        belong =i[i[:i.rindex("\\")].rindex('\\')+1:i.rindex("\\")]
                    else:
                        belong = os.path.join(other_p,i[i[:i.rindex("\\")].rindex('\\')+1:i.rindex("\\")])
                    print "%s:%s"%(belong,i)
                    self.queue.put([i,belong])
            for i in floders:
                self.AppendQueue(i,belong)

if __name__ == '__main__':
    if raw_input("C/S") == "c":
        c = Client()
        b = raw_input("Path:")
        c.AppendQueue(b)
        d=raw_input("Send?")
        eval(d)
    else:
        port = raw_input("port:")
        b = Server(int(port))
        b.Listen(20)
